import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { cleanObj } from "utils";

/**
 *    返回页面URL中，指定键的参数值
 */
export const useUrlQuery = <K extends string>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams();
  return [
    useMemo(
      () =>
        keys.reduce((pre, key) => {
          // console.log("searchParams.get(key)",searchParams.get(key));

          return { ...pre, [key]: searchParams.get(key) || "" };
        }, {} as { [key in K]: string }),
      [searchParams]
    ),
    (params: Partial<{ [key in K]: unknown }>) => {
      // console.log("{...Object.fromEntries(searchParams)}",{...Object.fromEntries(searchParams)});
      // console.log("{...params}",{...params});
      // console.log("last",{...Object.fromEntries(searchParams),...params});

      const o = cleanObj({ ...Object.fromEntries(searchParams), ...params });
      return setSearchParams(o);
    },
    // setSearchParams
  ] as const;
};
